package xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import org.junit.Test;
import reflection.Person;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.lang.reflect.Modifier;

/**
 * @author 吴阳基
 * @datetime 2024/1/3 11:55
 */
public class ShiLi2 {
    @Test
    public void test() throws ParserConfigurationException, IOException, SAXException {
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析XML文档，得到一个Document对象，即DOM树
        Document doc = db.parse("test/xml/shili1.xml");//收藏信息.xml为保存手机收藏信息的xml文档
//得到所有Brand节点列表信息
        NodeList brandList = doc.getElementsByTagName("Brand");
        //循环Brand信息
        for (int i = 0; i < brandList.getLength(); i++) {
            //获取第i个Brand元素信息
            Node brand = brandList.item(i);
            //获取第i个Brand元素的name属性的值
            Element element = (Element) brand;
            String attrValue = element.getAttribute("name");
            //获取第i个Brand元素的所有子元素的name属性值
            NodeList types = element.getChildNodes();
            for (int j = 0; j < types.getLength(); j++) {
                Node node = types.item(j);
                if(node.getNodeType() == Node.ELEMENT_NODE){
                    Element typeElement = (Element)node;
                    //获取属性值
                    String type = typeElement.getAttribute("name");//获得手机型号
                    System.out.println("手机:"+attrValue+type);
                }
            }
        }
    }
}
